#include"jiajia_lmcc.h"

extern unicode_t JiaJia_next_unicode(){
    JiaJia_file_pt jjfile = JiaJia_file_top();
    unicode_t c32 = JiaJia_stream_next_unicode(jjfile->stream);

    switch(c32){
    case 0x3010:                /* 【 */
        c32 = '[';
        break;
    case 0x3011:                /* 】 */
        c32 = ']';
        break;
    case 0x3002:                /* 。 */
        c32 = '.';
        break;
    case 0x3001:                /* 、 */
        c32 = '\\';
        break;
    case 0x201c:
    case 0x201d:
        c32 = '\"';             /* “” */
        break;
    }

    return Yu_unicode_half(c32);
}

extern void JiaJia_back_unicode(){
    JiaJia_file_pt jjfile = JiaJia_file_top();
    /* 保证 forward 指向非 EOF 且 forward != back 。 */
    if(jjfile->buf[jjfile->forward] != YU_UNICODE_EOF &&
       jjfile->forward != jjfile->back){
        jjfile->forward =
            (jjfile->forward == 0)? jjfile->buf_size-1:jjfile->forward-1;
    }
}

static unicode_t _JiaJia_throw_unicode(JiaJia_file_pt jjfile){
    unicode_t c32 = YU_UNICODE_EOF;
    if(jjfile->back != jjfile->forward){
        c32 = jjfile->buf[jjfile->back];
        jjfile->back = (jjfile->back == jjfile->buf_size-1)? 0:jjfile->back+1;
        /* 计算行和列 */
        if(c32 == '\n'){
            ++jjfile->rows;
            jjfile->cols = 1;
        }else{
            ++jjfile->cols;
        }
    }
    return c32;
}

extern unicode_t JiaJia_throw_unicode(){
    JiaJia_file_pt jjfile = JiaJia_file_top();
    return _JiaJia_throw_unicode(jjfile);
}

extern void JiaJia_throw_string(Yu_string_pt str){
    JiaJia_file_pt jjfile = JiaJia_file_top();

    unicode_t buf[256];
    size_t buf_top = 0;

    /* 如果返回 eof 证明 back 已经等于 forward */
    while((buf[buf_top] = _JiaJia_throw_unicode(jjfile)) != YU_UNICODE_EOF){
        ++buf_top;
        if(buf_top == 256){
            Yu_string_append_u32_buf(str, buf, buf_top);
            buf_top = 0;
        }
    }

    Yu_string_append_u32_buf(str, buf, buf_top);
}
